package com.sunday.aomi.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.common.widgets.NoScrollListview;
import com.sunday.aomi.R;
import com.sunday.aomi.ui.common.ShowBigImage;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.entity.order.OrderProduct;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.R.attr.order;
import static com.sunday.aomi.R.id.or;

/**
 * Created by 刘涛 on 2017/5/27.
 */

public class OrderDetailActivity extends BaseActivity {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.order_status)
    TextView orderStatus;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_addr)
    TextView userAddr;
    @Bind(R.id.order_no)
    TextView orderNo;
    @Bind(R.id.order_time)
    TextView orderTime;
    @Bind(R.id.list_view)
    NoScrollListview listView;
    @Bind(R.id.total_num)
    TextView totalNum;
    @Bind(R.id.total_money)
    TextView totalMoney;
    @Bind(R.id.rl_total_layout)
    RelativeLayout rlTotalLayout;
    @Bind(R.id.send_title)
    TextView sendTitle;
    @Bind(R.id.driver_name)
    TextView driverName;
    @Bind(R.id.driver_no)
    TextView driverNo;
    @Bind(R.id.driver_img)
    ImageView driver_img;
    @Bind(R.id.layout_driver)
    LinearLayout layout_driver;


    private long orderId;
    private OrderItem orderItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        orderId = getIntent().getLongExtra("orderId", 0);
        title.setText("订单详情");
        getData();
    }

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"orderId", "nonce"};
        String[] str2 = new String[]{String.valueOf(orderId), nonce};
        showLoadingDialog(0);
        Call<ResultDO<OrderItem>> call = MemberClient.getApiAdapter().getOrderDetail(orderId, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<OrderItem>>() {
            @Override
            public void onResponse(Call<ResultDO<OrderItem>> call, Response<ResultDO<OrderItem>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    orderItem = response.body().getResult();
                    updateView();

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<OrderItem>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private void updateView() {
        if (orderItem == null) {
            return;
        }
        orderStatus.setText(orderItem.getOrderStatusStr());
        userName.setText(String.format("%1$s  %2$s", orderItem.getReceiveName(), orderItem.getReceiveMobile()));
        userAddr.setText(orderItem.getReceiveAddress());
        orderNo.setText("订单号："+orderItem.getOrderNo());
        orderTime.setText(orderItem.getCreateDate());
        listView.setAdapter(new CommenAdapter<OrderProduct>(mContext, orderItem.getProducts(), R.layout.list_order_confirm_product) {
            @Override
            public void convert(ViewHolder helper, OrderProduct item, int position) {
                bind(helper, item);
            }
        });
        int num = 0;
        if (orderItem.getProducts() != null && orderItem.getProducts().size() > 0) {
            for (OrderProduct product : orderItem.getProducts()) {
                num += product.getNum();
            }
        }
        totalNum.setText(SpannalbeStringUtils.setTextColor("共计商品：", mContext.getResources().getColor(R.color.black_3)));
        totalNum.append((SpannalbeStringUtils.setTextColor(String.format("%d件", num), mContext.getResources().getColor(R.color.price_yellow))));
        totalMoney.setText(SpannalbeStringUtils.setTextColor("应付款：", mContext.getResources().getColor(R.color.black_3)));
        totalMoney.append(SpannalbeStringUtils.setTextColor(String.format("￥%s", orderItem.getPayAmount().setScale(2, RoundingMode.HALF_UP)), mContext.getResources().getColor(R.color.price_yellow)));
        driverName.setText(TextUtils.isEmpty(orderItem.getDriverName())?"":
        String.format("配送员：%1$s  手机号：%2$s",orderItem.getDriverName(),orderItem.getDriverMobile()));
        driverNo.setText(TextUtils.isEmpty(orderItem.getDriverCarNo())?"":"货运车牌："+orderItem.getDriverCarNo());
        sendTitle.setText(!TextUtils.isEmpty(orderItem.getDriverMobile())?"配送信息：":"配送信息：暂无");
        if (!TextUtils.isEmpty(orderItem.getDriverImage())){
            Picasso.with(mContext)
                    .load(orderItem.getDriverImage())
                    .resize(100,100)
                    .into(driver_img);
        }
        //layout_driver.setVisibility(TextUtils.isEmpty(orderItem.getDriverMobile())? View.GONE:View.VISIBLE);

    }

    private void bind(ViewHolder helper, OrderProduct item) {
        ImageView imageView = helper.getView(R.id.product_img);
        if (!TextUtils.isEmpty(item.getImage())) {
            Picasso.with(mContext)
                    .load(item.getImage())
                    .error(R.mipmap.ic_default)
                    .resize(150, 150)
                    .into(imageView);
        }
        ((TextView) helper.getView(R.id.product_title)).setText(item.getName());
        ((TextView) helper.getView(R.id.product_price)).setText(String.format("￥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
        ((TextView) helper.getView(R.id.product_num)).setText(String.format("X%d", item.getNum()));
        ((TextView) helper.getView(R.id.product_spec)).setText(item.getStandard());
    }

    @OnClick(R.id.driver_img)
    void showBigImg(){
        intent = new Intent(mContext, ShowBigImage.class);
        intent.putExtra("imgPath",orderItem.getDriverImage());
        startActivity(intent);
    }

}
